import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from collections import Counter
import warnings
warnings.filterwarnings('ignore')

# 设置中文字体支持
plt.rcParams['font.sans-serif'] = ['SimHei', 'Arial Unicode MS', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

# 读取CSV文件
df = pd.read_csv('douban_top250.csv')

# 数据清洗：移除关键字段为空的行
df = df.dropna(subset=['title', 'director', 'genre', 'region', 'year'])

print("数据概览:")
print(df.info())
print("\n基本统计信息:")
print(df.describe())

# 创建图表目录
import os
if not os.path.exists('charts'):
    os.makedirs('charts')


# 3. 不同类型的电影数量
# 提取所有类型并统计
all_genres = []
for genre in df['genre'].dropna():
    genres = [g.strip() for g in genre.split(' ')]
    all_genres.extend(genres)

genre_count = Counter(all_genres)
top_genres = dict(genre_count.most_common(10))

plt.figure(figsize=(12, 8))
genres = list(top_genres.keys())
counts = list(top_genres.values())
bars = plt.bar(range(len(genres)), counts, color='lightcoral')
plt.xlabel('电影类型')
plt.ylabel('电影数量')
plt.title('Top10电影类型分布')
plt.xticks(range(len(genres)), genres, rotation=45, ha='right')
# 在柱子上显示数值
for bar, count in zip(bars, counts):
    plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5, 
             str(count), ha='center', va='bottom')
plt.tight_layout()
plt.savefig('charts/genre_distribution.png', dpi=300, bbox_inches='tight')
plt.close()

# 4. 不同地区的电影数量
# 提取所有地区并统计
all_regions = []
for region in df['region'].dropna():
    regions = [r.strip() for r in region.split(' ')]
    all_regions.extend(regions)

region_count = Counter(all_regions)
top_regions = dict(region_count.most_common(10))

plt.figure(figsize=(12, 8))
regions = list(top_regions.keys())
counts = list(top_regions.values())
bars = plt.bar(range(len(regions)), counts, color='lightgreen')
plt.xlabel('地区')
plt.ylabel('电影数量')
plt.title('Top10地区电影分布')
plt.xticks(range(len(regions)), regions, rotation=45, ha='right')
# 在柱子上显示数值
for bar, count in zip(bars, counts):
    plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5, 
             str(count), ha='center', va='bottom')
plt.tight_layout()
plt.savefig('charts/region_distribution.png', dpi=300, bbox_inches='tight')
plt.close()


# 6. 各年代电影数量分布
decades = {}
for year_str in df['year'].dropna():
    try:
        year = int(float(year_str))
        decade = (year // 10) * 10  # 计算年代
        decade_str = f"{decade}s"
        if decade_str not in decades:
            decades[decade_str] = 0
        decades[decade_str] += 1
    except:
        pass

# 按年代排序
sorted_decades = dict(sorted(decades.items(), key=lambda x: x[0]))

plt.figure(figsize=(12, 8))
decade_labels = list(sorted_decades.keys())
counts = list(sorted_decades.values())
bars = plt.bar(range(len(decade_labels)), counts, color='mediumpurple')
plt.xlabel('年代')
plt.ylabel('电影数量')
plt.title('各年代电影数量分布')
plt.xticks(range(len(decade_labels)), decade_labels, rotation=45, ha='right')
# 在柱子上显示数值
for bar, count in zip(bars, counts):
    plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5, 
             str(count), ha='center', va='bottom')
plt.tight_layout()
plt.savefig('charts/decade_distribution.png', dpi=300, bbox_inches='tight')
plt.close()

# 4. 高分电影导演TOP10
# 统计导演作品数量
director_counts = {}
for _, row in df.iterrows():
    if pd.notna(row['director']):
        director = row['director'].strip()
        if director != "":
            if director not in director_counts:
                director_counts[director] = 0
            director_counts[director] += 1

# 排序并选取前10
top_directors = dict(sorted(director_counts.items(), key=lambda x: x[1], reverse=True)[:10][::-1])

plt.figure(figsize=(12, 8))
directors = list(top_directors.keys())
counts = list(top_directors.values())
bars = plt.barh(range(len(directors)), counts, color='teal')
plt.ylabel('导演')
plt.xlabel('作品数量')
plt.title('作品数量最多的导演TOP10')
plt.yticks(range(len(directors)), directors)
# 在柱子末端显示数值
for i, (bar, count) in enumerate(zip(bars, counts)):
    plt.text(bar.get_width() + 0.1, bar.get_y() + bar.get_height()/2, 
             str(count), ha='left', va='center')
plt.tight_layout()
plt.savefig('charts/top_directors.png', dpi=300, bbox_inches='tight')
plt.close()

print("数据分析完成，图表已保存到 'charts' 文件夹中。")